// store统一设置
export const setCache = (key: string, value: any) => {
    if (!key) throw new Error('key is required');
    uni.setStorageSync(`QY_${key?.toUpperCase()}`, value);
};
export const getCache = (key: string) => {
    if (!key) throw new Error('key is required');
    return uni.getStorageSync(`QY_${key?.toUpperCase()}`);
};
export const removeCache = (key: string) => {
    if (!key) throw new Error('key is required');
    uni.removeStorageSync(`QY_${key?.toUpperCase()}`);
};

// 随机ID
export const genId = (prefix?: number | string) =>
    `${prefix || ''}${Math.random().toString(16).slice(2)}`;

// 将数组映射为对象
export const ArrToObj = (
    arr: anyObj[],
    key = 'code',
    value = 'value',
): { [key: string]: string } => {
    const obj: anyObj = {};
    let i = 0;
    for (i; i < arr.length; i++) {
        obj[arr[i][key]] = arr[i][value];
    }
    return obj;
};

// 延迟运行
export const $sleep = (time: number) => {
    return new Promise(res => {
        const timeout = setTimeout(() => {
            res(0);
            clearTimeout(timeout);
        }, time);
    });
};

export function formCheck(rules: anyObj[], data: anyObj) {
    let res = true;
    for (const i of rules) {
        if (i instanceof Array) {
            for (const j of i) {
                if (j.required && !data[j.prop]) {
                    res = false;
                    uni.showToast({
                        title: j.message,
                        icon: 'none',
                    });
                    break;
                }
                if (j.validator) {
                    j.validator(data, data[j.prop], (result: any) => {
                        if (result instanceof Error) {
                            res = false;
                            uni.showToast({
                                title: j.message,
                                icon: 'none',
                            });
                        }
                    });
                }
            }
        } else {
            if (i.required && !data[i.prop]) {
                res = false;
                uni.showToast({
                    title: i.message,
                    icon: 'none',
                });
                break;
            }
        }
    }
    return res;
}
// // uniApi转换成同步
// function general(config: anyObj, method?: string) {
//     return new Promise((resolve, reject) => {
//         if (method) {
//             (uni as any)[method]({
//                 ...config,
//                 success(res: any) {
//                     resolve(res);
//                 },
//                 fail(err: any) {
//                     reject(err);
//                 },
//             });
//         }
//     });
// }
// export const uniSync = {
//     general,
//     chooseMedia: (...args: any[]) => general(args),
// };
/**
 * 文件上传
 * @param
 * @returns
 */
export const uploadFile = path =>
    new Promise((resolve, reject) => {
        uni.uploadFile({
            url: `${import.meta.env.VITE_HOST}/api/main/sysFileInfo/tenUploadAll`,
            filePath: path,
            name: 'file',
            header: {
                Authorization: `Bearer ${getCache('token')}`,
                'Content-Type': 'application/form-data',
            },
            success: uploadFileRes => {
                const data = JSON.parse(uploadFileRes.data);
                console.log('data', data, data.data.filePath);
                if (uploadFileRes.statusCode === 200) {
                    resolve(data.data.filePath);
                } else {
                    reject(data.message);
                }
            },
            fail: error => {
                console.log('err', error);
                reject(error);
            },
        });
    });
